package indi.h.filefilter.filters;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import indi.h.filefilter.anaysis.Anaysis;
import indi.h.filefilter.enums.FilterRtEnum;

public class StrFilter extends BasicFilter {
	private final static Logger l = Logger.getLogger(StrFilter.class);
	private String[] intercept;
	private int max_length;
	private StringBuffer msg_buffer;
	private List<StrNode> nodes;

	public StrFilter(Enum title, String[] intercept) {
		// TODO Auto-generated constructor stub
		super(title);
		this.intercept = intercept;
		for (String s : this.intercept) {
			max_length = s.length() > max_length ? s.length() : max_length;
		}
		this.msg_buffer = new StringBuffer("");
		nodes = new ArrayList<>();
	}

	@Override
	public boolean filter(Anaysis.FileMessage af) {
		// TODO Auto-generated method stub
		super.filter(af);
		if (isFilter()) {
			rsMsgBuffer(af.getMessage());
			//l.debug(msg_buffer);
			for (String i : intercept) {
				if (this.msg_buffer.indexOf(i) > -1) {
					setF_R(new FilterR(FilterRtEnum.CONTENT, i));
					return false;
				}
			}
		}
		return true;
	}

	public void rsMsgBuffer(String msg) {
		if (nodes.size() < 2) {
			nodes.add(new StrNode(msg_buffer.length(), msg.length()));
			msg_buffer.append(msg);
			return;
		}
		while (nodes.size() > 1) {
			StrNode take = nodes.get(0);
			if ((msg_buffer.length() - take.getLength()) > max_length) {
				msg_buffer.delete(0, take.getLength());
				nodes.remove(0);
			} else
				break;
		}
		nodes.add(new StrNode(msg_buffer.length(), msg.length()));
		msg_buffer.append(msg);
	}

	private class StrNode {
		private int index;
		private int length;

		public StrNode(int index, int length) {
			super();
			this.index = index;
			this.length = length;
		}

		public int getIndex() {
			return index;
		}

		public int getLength() {
			return length;
		}
	}
}
